package com.tensquare.spit.service;

import com.tensquare.spit.pojo.Spit;
import com.tensquare.spit.spitdao.SpitDao;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.Date;
import java.util.List;

/**
 * Created with IDEA
 * author:zhiXiang-Chen
 * Date:2019/3/2
 * Time:9:55
 */
@Service
public class SpitService {

    @Autowired
    private SpitDao spitDao;

    @Autowired
    private IdWorker idWorker;

    public void add(Spit spit) {
        spit.set_id(idWorker.nextId()+"");

        spit.setPublishtime(new Date());//发布日期
        spit.setVisits(0);//浏览量
        spit.setShare(0);//分享数
        spit.setThumbup(0);//点赞数
        spit.setComment(0);//回复数
        spit.setState("1");//状态

        if (spit.getParentid()!=null && !"".equals(spit.getParentid())){
            //封装条件
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spit.getParentid()));

            //封装数据
            Update update = new Update();
            update.inc("comment",1);
            //更新
            mongoTemplate.updateFirst(query,update,"spit");
        }

        spitDao.save(spit);
    }

    public List<Spit> findAll() {
        return  spitDao.findAll();
    }

    public Spit findById(String spitId) {
        return  spitDao.findById(spitId).get();
    }
    public void update(Spit spit) {
        spitDao.save(spit);
    }

    public void deleteById(String spitId) {
        spitDao.deleteById(spitId);
    }

    public Page<Spit> findByParentId(String parentId, int page, int size) {
        PageRequest pageRequest = PageRequest.of(page-1,size);
        return  spitDao.findByParentid(parentId,pageRequest);
    }

    @Autowired
    private MongoTemplate mongoTemplate;

    public void updateThumbup(String spitId) {
        //封装条件
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(spitId));

        //封装数据
        Update update = new Update();
        update.inc("thumbup",1);

        //spit:collection的name
        mongoTemplate.updateFirst(query,update,"spit");
    }
}
